
package galaxy.app.network.rpc.handler;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import galaxy.app.Galaxy;
import galaxy.app.dispatch.DispatcherSystem;
import galaxy.app.dispatch.executor.RpcCallbackPacketExecutor;
import galaxy.app.log.LogHelper;
import galaxy.app.network.rpc.client.RpcCallbackContext;
import galaxy.app.network.rpc.client.RpcFutureContext;
import galaxy.app.network.rpc.packet.RpcCallbackPacket;


/**
 */
@Sharable
public class RpcCallbackHandler extends BaseChannelHandler<RpcCallbackPacket> {

    private RpcFutureContext futureContext;
    DispatcherSystem dispatch;

    public RpcCallbackHandler( RpcFutureContext futureContext) {
        super(RpcCallbackPacket.class);
        this.futureContext = futureContext;
        dispatch = Galaxy.systems().get(DispatcherSystem.class);
    }

    @Override
    protected void onChannelRead(ChannelHandlerContext ctx, RpcCallbackPacket packet) {
        // if (RPC_LOGGER.isDebugEnabled()) {
            LogHelper.debug("<----- receive msg. {}", packet);
        // }

        //TODO 这里是性能瓶颈
        RpcCallbackContext callbackContext = futureContext.getCallback(packet.sequenceId);
        if (callbackContext != null) {
            dispatch.publish(new RpcCallbackPacketExecutor(callbackContext, packet));
        } else {
            futureContext.notifyRpcMessage(packet);
        }
    }

//    @Override
//    public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) {
//        LOGGER.error("----- nodeType = {}, nodeId = {} connect closed.", nodeType, nodeId);
//        LOGGER.error("{}", throwable.getMessage());
//        ctx.close();
//    }
}
